
#include "file_rw.h"

int FILE_File2Mem( char* acFileName, char** pAddrDestMem, long* plFileLen )
{
	/* open file */
	FILE* pFile = fopen( acFileName, "rb" );
	if( NULL == pFile )
	{
		return -1;
	}
	
	/* get length */
	fseek( pFile,0,SEEK_END);
	long lLen = ftell( pFile );
	
	/* rewind to the head */
	fseek( pFile,0,SEEK_SET);
	
	/* get memory */
	char* pBuf = (char*)malloc( lLen );
	if( NULL == pBuf )
	{
		fclose( pFile );
		return -1;
	}
	
	/* file -> mem */
	fread( pBuf, lLen, 1, pFile );
	
	/* clean up */
	fclose( pFile );
	
	/* return values */
	*pAddrDestMem = pBuf;
	*plFileLen = lLen;
	
	return 0;
}

int FILE_Mem2File( char* acFileName, char* pSrcMem, long lLen )
{
	/* open file */
	FILE* pFile = fopen( acFileName, "wb" );
	if( NULL == pFile )
	{
		return -1;
	}
	
	/* file -> mem */
	fwrite( pSrcMem, lLen, 1, pFile );
	
	/* clean up */
	fclose( pFile );
	
	return 0;
}

int FILE_GetLength( char* acFileName, long* plFileLen )
{
	/* open  */
	FILE* pFile = fopen( acFileName, "rb" );
	if( NULL == pFile )
	{
		return -1;
	}
	
	/* get length */
	fseek( pFile,0,SEEK_END);
	long lLen = ftell( pFile );
	
	/* clean up */
	fclose( pFile );
	
	/* return values */
	*plFileLen = lLen;
	
	return lLen;
}